//
//  TJEmotionKeyBoard.swift
//  testDate
//
//  Created by 唐后能 on 16/4/20.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit

class TJEmotionKeyBoard: UIView {

    private let ReuseIdentifier:String = "ReuseIdentifier"
    
    // 表情键盘对应的textView.
    var textView:UITextView?
    
    // MARK - 初始化方法.
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        let newFrame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 216)
        super.init(frame: newFrame)
        prepareUI()
    }

    private func prepareUI(){
        backgroundColor = UIColor.brownColor()
        // 1,添加子控件.
        addSubview(collectionView)
        addSubview(emotionToolBar)
        addSubview(pageControl)
        
        // 2,添加约束.
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        emotionToolBar.translatesAutoresizingMaskIntoConstraints = false
        pageControl.translatesAutoresizingMaskIntoConstraints = false
        // collectionView.
        addConstraint(NSLayoutConstraint(item: collectionView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: collectionView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: collectionView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: collectionView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: emotionToolBar, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0))
        // emotionToolBar.
        addConstraint(NSLayoutConstraint(item: emotionToolBar, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: emotionToolBar, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: emotionToolBar, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: emotionToolBar, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 44))
        // pageConrol
        addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: collectionView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: collectionView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
        
        
    }
    
    // 给collectionView的cell的itemSize赋值.
    override func layoutSubviews() {
        super.layoutSubviews()
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = collectionView.frame.size
    }
    
    
    // 判断scrollView是否包含某个点.
    
    // MARK - 懒加载子控件.
    // collectionView.
    private lazy var collectionView:UICollectionView = {
    
        let flowLayout = UICollectionViewFlowLayout()
        let cv = UICollectionView(frame: CGRectZero, collectionViewLayout: flowLayout)
        cv.backgroundColor = UIColor.brownColor()
        // 设置.
//        flowLayout.itemSize = cv.bounds.size //此处设置无效,因为此时还不知道collectionView的大小.
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.minimumLineSpacing = 0
        flowLayout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        cv.pagingEnabled = true
        cv.bounces = false
        cv.showsHorizontalScrollIndicator = false
        
        // 注册cell.
        cv.registerClass(TJEmotionViewCell.self, forCellWithReuseIdentifier: self.ReuseIdentifier)
        
        // 设置数据源,代理.
        cv.dataSource = self
        cv.delegate = self
        
        return cv
    }()
    
    // 懒加载tooBar.
    private lazy var emotionToolBar:TJEmotionToolBar = {
    
        let toolBar = TJEmotionToolBar.loadEmotionToolBar()
        // 设置toolBar的代理属性.
        toolBar.delegate = self
        
        return toolBar
    }()
    
    // 懒加载pageControl.
    private lazy var pageControl:UIPageControl = {
    
        let control = UIPageControl()
        // 设置. 页数要在滚动collectionView,或点击按钮的时候显示.
        control.hidden = true
        control.currentPageIndicatorTintColor = UIColor.redColor()
        control.pageIndicatorTintColor = UIColor.blackColor()
        // _pageImage   普通的
        // _currentPageImage    选中的
        control.setValue(UIImage(named: "compose_keyboard_dot_normal"), forKey: "_pageImage")
        control.setValue(UIImage(named: "compose_keyboard_dot_selected"), forKey: "_currentPageImage")
        
        return control
    }()
    
    // 设置pageControl显示的页数.
    private func setPageCounts (indexPath:NSIndexPath){
    
        pageControl.hidden = false
        pageControl.numberOfPages = indexPath.section != 0 ? TJEmotionManager.shareEmotionManager.emotionPackages[indexPath.section].pageEmotions.count : 0
        pageControl.currentPage = indexPath.item
}
    
    
    // TODO:collectionView模拟的组和cell数量
//    private let items = [1, 6, 4, 2]
}


// MARK - collectionView的数据源和代理方法.
extension TJEmotionKeyBoard:UICollectionViewDataSource,UICollectionViewDelegate {

    // MARK - 数据源方法.
    // 组数.
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return TJEmotionManager.shareEmotionManager.emotionPackages.count
    }
    // 每组的表情个数.
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return TJEmotionManager.shareEmotionManager.emotionPackages[section].pageEmotions.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ReuseIdentifier, forIndexPath: indexPath) as! TJEmotionViewCell
        cell.indexPath = indexPath
        // 传递模型数据.
        cell.emotionPackage = TJEmotionManager.shareEmotionManager.emotionPackages[indexPath.section].pageEmotions[indexPath.item]
        
        // 设置cell的代理.
        cell.delegate = self
        return cell
    }
    
    // MARK - 代理方法.
    // 判断参考点在哪一页可见的cell上.
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        // 定义中心参考点.
        let refPoint = CGPointMake(self.bounds.size.width*0.5+scrollView.contentOffset.x, self.bounds.size.height*0.5)
        
        // 获取indexPath的方法1:
        let indexPath1 = collectionView.indexPathForItemAtPoint(refPoint)
//        print(indexPath1?.section)
        emotionToolBar.switchToBtnWithNum(indexPath1!.section)
        
        // 获取indexPath方法2:
//        for cell in collectionView.visibleCells() {
//        
//            if cell.frame.contains(refPoint) {
//                // 让tooBar选中对应的Btn.
//                let indexPath = collectionView.indexPathForCell(cell)
//                
//                if indexPath != nil {
//                    print(indexPath?.section)
//                    emotionToolBar.switchToBtnWithNum(indexPath!.section)
//                    break
//                }
//            }
//        }
        
        // 设置pageControl的页数.
        setPageCounts(indexPath1!)
    }
}



// MARK: - 其它view的代理方法.
extension TJEmotionKeyBoard:TJEmotionToolBarDelegate,TJEmotionViewCellDelegate{
    
    // toolBar的代理方法,toolBar上按钮点击事件.
    func emotionToolBar(emotionToolBar: TJEmotionToolBar, emotionType: TJEmotionToolBarBtnType) {
        // 让collectionView滚动到指定组的第0页.
        let indexPath = NSIndexPath(forItem: 0, inSection: emotionType.rawValue)
//        print("indexPath: \(indexPath)")
        //        print("\(indexPath)")
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        
        // 设置pageControl显示的页数.
        setPageCounts(indexPath)
    }
    
    // cell的代理方法.-->表情按钮点击事件.
    func emotionViewCellEmotionBtnClicked(emotion: TJEmotion) {
     
        //1,将表情模型添加到textVeiw中.
//        insertEmotionToTextView(emotion)
        textView?.insertEmotionToTextView(emotion)
        
        // 2,将表情模型添加到最近表情的cell中.
        TJEmotionManager.shareEmotionManager.addEmotionToRecent(emotion)
    }
    
    // 删除按钮的点击事件.
    func emoticonViewCellDeleteButtonClicked(cell: TJEmotionViewCell) {
        textView?.deleteBackward()
    }
    
    // 将点击的表情添加到textVew中.-->抽取到UITextView的分类中.
//    private func insertEmotionToTextView(emotion:TJEmotion){
//    
//        // 1,点击的是emoji表情.-->添加text文本.
//        if let emoji = emotion.emoji {
//            
//            textView?.insertText(emoji)
//            return
//        }
//        
//        // 2,点击的是图片或浪小花.-->添加属性文本.
//        if let pic = emotion.fullPngPath {
//            
//            // 将图片添加textView, textView可以显示属性文本
//            // 1.根据图片准备好附件.
//            // 创建附件,并将图片赋值给附件的image属性.
//            let attachment = NSTextAttachment()
//            attachment.image = UIImage(named: pic)
//            
//            // 获取文本的高度
//            let height = textView?.font?.lineHeight ?? 10
//            
//            // 设置附件的大小
//            attachment.bounds = CGRect(x: 0, y: -4, width: height, height: height)
//            
//            // 2.根据附件创建属性文本
//            //            let attrString = NSAttributedString(attachment: attachment) // 此方式,后面的插入的图片会变小.
//            //// 创建带附件的属性文本,并且添加font属性-->如果没有添加font属性,在表情图片后面再插入的图片会变小.
//            let attrString = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
//            attrString.addAttribute(NSFontAttributeName, value: textView!.font!, range: NSRange(location: 0, length: 1))
//            
//            // 根据textView现有属性文本创建可变的属性文本.
//            let attrStringM = NSMutableAttributedString(attributedString: (textView?.attributedText)!)
//            
//            // 记录光标位置.
//            let selectedRange = textView!.selectedRange
//            
//            // 改变可变文本内容->将textView将要显示的文本把光标选中位置给替换.
//            attrStringM.replaceCharactersInRange((textView?.selectedRange)!, withAttributedString: attrString)
//            //
//            // 3.textView设置属性文本
//            textView?.attributedText = attrStringM
//            
//            // 重新设置光标位置
//            textView?.selectedRange = NSRange(location: selectedRange.location + 1, length: 0)
//            
//        }
//
//    }
}